package common

import (
	"github.com/dgrijalva/jwt-go"
	"testPaper/model"
	"time"
)

var jwtKey = []byte("a_select_creat")

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

// CreatToken 小程序端生成token
func CreatToken(wxUser model.WxUser) (string, error) {
	// 设置过期时间
	expirationTime := time.Now().Add(24 * time.Hour)

	claims := &Claims{
		UserId: wxUser.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "ocean learn.tech",
			Subject:   "user token",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtKey)

	if err != nil {
		return "", err
	}
	return tokenString, err
}

// ParseToken token逆向解析代码
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtKey, nil
	})
	return token, claims, err
}

// CreatWebToken web端生成token
func CreatWebToken(admin model.Admin) (string, error) {
	// 设置过期时间
	expirationTime := time.Now().Add(24 * time.Hour)

	claims := &Claims{
		UserId: admin.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "ocean learn.tech",
			Subject:   "user token",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtKey)

	if err != nil {
		return "", err
	}
	return tokenString, err
}
